package com.example.seckilldemo.config;

import com.example.seckilldemo.exception.GlobalException;
import com.example.seckilldemo.pojo.User;
import com.example.seckilldemo.service.IUserService;
import com.example.seckilldemo.utils.CookieUtil;
import com.example.seckilldemo.vo.RespBean;
import com.example.seckilldemo.vo.RespBeanEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Author Wangbaba
 * @Date 2024/3/22 1:06
 * @Version 1.0
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handle)throws Exception{
        if (handle instanceof HandlerMethod){
            User user=getUser(request,response);
            UserContext.setUser(user);
            HandlerMethod hm= (HandlerMethod) handle;
            AccessLimit accessLimit=hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit==null){
                return true;
            }
            int second=accessLimit.second();
            int maxCount=accessLimit.maxCount();
            boolean needLogin=accessLimit.needLogin();
            String key=request.getRequestURI();
            if (needLogin){
                if (user==null){
                    render(response,RespBeanEnum.SESSION_ERROR);
                    return false;
                }else {
                    key+=":"+user.getId();
                }
                ValueOperations valueOperations=redisTemplate.opsForValue();
                //限制访问次数，5s5次
                Integer uriCount= (Integer) valueOperations.get(key);
                if (uriCount==null){
                    valueOperations.set(key,1,5, TimeUnit.SECONDS);
                }else if (uriCount<5){
                    valueOperations.increment(key);
                }else {
                    render(response,RespBeanEnum.ACCESS_ERROR);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 构建返回对象
     * @param request
     * @param response
     */
    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out =response.getWriter();
        RespBean respBean=RespBean.error(respBeanEnum);
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }

    /**
     * 获取当前登录用户
     */
    private User getUser(HttpServletRequest request, HttpServletResponse response){
        String ticket= CookieUtil.getCookieValue(request,"userTicket");
        if (StringUtils.isEmpty(ticket)){
            return null;
        }
        return userService.getUserByCookie(ticket,request,response);
    }

}